import React, { Fragment, useRef } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import {
	decrement,
	increment,
	asyncIncrement,
	oddIncrement,
} from '../../redux/slices/count'

const Count = () => {
	const dispatch = useDispatch()

	const select = useRef()

	const count = useSelector(state => state.count.value)
	const persons = useSelector(state=>state.persons.value)
	const personNum = persons.length

	const odd = () => {
		if (count % 2 !== 0) {
			dispatch(oddIncrement(select.current.value * 1))
		}else return
	}
	return (
		<Fragment>
			<h1>当前为Count组件，Person组件中人数为{personNum}</h1>
			<h4>当前求和为：{count}</h4>
			<select ref={select}>
				<option value="1">1</option>
				<option value="2">2</option>
				<option value="3">3</option>
			</select>
			&nbsp;
			<button onClick={() => dispatch(increment(select.current.value * 1))}>
				+
			</button>
			&nbsp;
			<button onClick={() => dispatch(decrement(select.current.value * 1))}>
				-
			</button>
			&nbsp;
			<button onClick={odd}>当前求和为奇数再加</button>
			&nbsp;
			<button
				onClick={() => dispatch(asyncIncrement(select.current.value * 1, 500))}
			>
				异步加
			</button>
			&nbsp;
		</Fragment>
	)
}

export default Count
